import * as THREE from 'three';


import './index.css'

// 轨道控制器
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';

/**
 * Cursor
 */
const cursor = {
    x: 0,
    y: 0
}
window.addEventListener('mousemove', (event) => {
    cursor.x = event.clientX / Sizes.width - 0.5
    cursor.y = -(event.clientY / Sizes.height - 0.5)
})

// Canvas
const canvas = document.querySelector("canvas.webgl");

// Scene
const scence = new THREE.Scene();

// Object
// const geometry = new THREE.BoxGeometry(1, 1, 1,2,2,2)


/**
三角形
const  positionsArray = new Float32Array([
    0,0,0,
    0,1,0,
    1,0,0
])
 */


const geometry = new THREE.BufferGeometry()

const count = 50;
const positionsArray = new Float32Array(count * 3 * 3)  //50个三角形   一个三角形3个点    一点三个值x,y,z

for (let i = 0; i < count * 3 * 3; i++) {
    positionsArray[i] = Math.random()
}
const positionAttribute = new THREE.BufferAttribute(positionsArray,3);
geometry.setAttribute('position', positionAttribute)



const material = new THREE.MeshBasicMaterial({
    color: '#ff0000',
    wireframe: true
})
const mesh = new THREE.Mesh(geometry, material);
scence.add(mesh)


// Sizes
const Sizes = {
    width: window.innerWidth,
    height: window.innerHeight
}

window.addEventListener('resize', () => {
    // Update size
    Sizes.width = window.innerWidth
    Sizes.height = window.innerHeight

    // Update camera
    camera.aspect = Sizes.width / Sizes.height
    camera.updateProjectionMatrix()

    // Updaet renderer
    renderer.setSize(Sizes.width, Sizes.height)
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
})

window.addEventListener('dblclick', () => {
    const fullscreenElement = document.fullscreenElement
    if (!fullscreenElement) {
        canvas.requestFullscreen()
    } else {
        document.exitFullscreen()
    }
})


// Camera 
// 透视相机就是  物体离得近变大，离远变小    角度（45~75度较为合适）  宽/高   near  far(太小会导致看不全    太大看的太多，比如我们看一个村子，村子后面的山不需要看见，far需要一个合适的值)
const camera = new THREE.PerspectiveCamera(75, Sizes.width / Sizes.height, 1, 100)

// 相机的初始位置在（0，0，0）中心点，看不见物体，移动相机
camera.position.z = 3

scence.add(camera)


// Controls
const controls = new OrbitControls(camera, canvas);
// controls.enabled = false //禁用
controls.enableDamping = true  //添加阻尼效果  修改之后需要update
// controls.target.y = 1
// controls.update()


// Renderer
const renderer = new THREE.WebGLRenderer({
    canvas,
})
renderer.setSize(Sizes.width, Sizes.height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))  //解决抗锯齿,不需要超过2，避免性能浪费 

const tick = () => {
    controls.update()
    // Render
    renderer.render(scence, camera);
    window.requestAnimationFrame(tick);
}

tick()